import React, { useEffect, useState, useRef } from 'react'
import { connect, useDispatch } from "react-redux";
import dayjs from 'dayjs';
import FullCalendar from '@fullcalendar/react'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction';
// import timelinePlugin from '@fullcalendar/timeline';
import './index.scss'
import { View, Text } from '@tarojs/components'
import Taro, { useTabItemTap } from '@tarojs/taro'

// import { useHistory } from 'react-router-dom';

function App(props) {
    useEffect(() => { }, [])
    const [scrollTime, setScrollTime] = useState(dayjs().format('HH:mm:ss'));
    console.log(scrollTime, 'scrollTime');

    const {
        datalist,
        onClickItem,
        date
    } = props

    const scheduleList = [];
    datalist &&
        datalist.forEach((item: any) => {
            item.color = item.beCourse == 1 ? 'rgb(255,247,242)' : 'rgb(242,250,255)'
            item.textColor = item.beCourse == 1 ? 'rgb(255,102,0)' : 'rgb(0,134,223)'
            item.title = item.scheduleTitle
            item.class = item.className
            item.times = parseInt(new Date(item.scheduleDate + ' ' + item.endTime) - new Date(item.scheduleDate + ' ' + item.startTime)) / 1000 / 60
            item.startTime1 = item.startTime
            item.endTime1 = item.endTime
            if (item.beAllDay == '1') return;
            scheduleList.push(item);
            return scheduleList;
        })

    const eventClick = (eventInfo: any) => {
        console.log(eventInfo.event._def, 'eventInfo.event._def.extendedProps');

        onClickItem(eventInfo.event._def.extendedProps)
    }

    const renderEventContent = (eventInfo) => {
        let data = eventInfo.event._def.extendedProps;

        return (
            <View className='schedule-container'>
                <View className={data.beCourse == '0' ? 'schedule-title' : 'schedule-title schedule-title-course'}>{data.beCourse == '0' ? data.scheduleTitle : data.scheduleContent}
                    {data.beCourse == '1' ?
                        <View className='schedule-course'><Text className='schedule-course-text'>{data.scheduleMark}课</Text></View> : ''
                    }</View>
                {
                    data.times < 45 ? '' : <View className={data.beCourse == '0' ? 'schedule-location' : 'schedule-location schedule-location-course'}>
                        <Text className='schedule-content' style={{ marginRight: data.scheduleContent || data.class ? '' : '0' }}>{data.beCourse == '0' ? data.scheduleContent : data.class}</Text>
                        {/* {data.beCourse == '1' ? <Text className='schedule-content'>{data.class}</Text> : ''} */}
                        <Text className='address'>{data.scheduleLocation ? (data.scheduleContent || data.class ? '(' : '') + data.scheduleLocation + (data.scheduleContent || data.class ? ')' : '') : ''}</Text>
                    </View>
                }
            </View>
        )
    }
    const [oldEl, setOldEl] = useState(new Object());
    const dateClick = (selectInfo) => {
        const calendarApi = selectInfo.view.calendar;
        console.log(calendarApi, 'calendarApi');

        calendarApi.unselect(); // 清除当前选择

        setOldEl(selectInfo);
        // selectInfo.jsEvent.target.style.backgroundColor = 'red'

        // if(selectInfo == oldEl){
        if (selectInfo.jsEvent.target.style.backgroundColor === 'red') {
            let start = selectInfo.date
            selectInfo.jsEvent.target.addEventListener('click', () => {
                // TODO: 进入新建日程页面
                // let url = '/pages/scheduleApp/createSchedule/index?startDate=' + date + '&start=' + dayjs(start).format('HH:mm:ss') + '&end=' + dayjs(start).add(1, 'h').format('HH:mm:ss')
                // Taro.navigateTo({
                //     url
                // })
            })
            // selectInfo.jsEvent.target.style.backgroundColor = '#fff'

        } else {
            selectInfo.jsEvent.target.style.backgroundColor = 'red'
        }
        // }
        console.log(selectInfo, 'info', oldEl);
    }
    const [currentTime, setCurrentTime] = useState<Date>(new Date());
    const calendarRef = useRef(null);
    useEffect(() => {
        const calendarApi = calendarRef.current.getApi();
        // let startTime1 = dayjs().format('HH:mm:ss')
        // calendarApi.scrollToTime(startTime1);
        let next = calendarApi.el.childNodes[0].childNodes[2].childNodes[1].childNodes[1];
        next.click();
        let today = calendarApi.el.childNodes[0].childNodes[2].childNodes[0];
        today.click();
        console.log(calendarApi, 'calendarApi');

        const currentDate = calendarApi.getDate();
        // 获取每个时间段的持续时间，假设为30分钟
        const slotDuration = calendarApi.getOption('slotDuration');
        // 计算当前时间的起始时间
        const startTime = new Date(currentTime.getFullYear(), currentTime.getMonth(), currentTime.getDate(), currentTime.getHours(), Math.floor(currentTime.getMinutes() / 30) * 30);
        console.log(dayjs(startTime).format('HH:mm:ss'), 'startTime');

        setCurrentTime(startTime);

        let a = document.getElementsByClassName('fc-timegrid-now-indicator-arrow')
        console.log(a, 'aaaa');
        a[0].innerHTML = dayjs(currentTime).format('HH:mm')
    }, []);
    const selectOverlap = (event) => {
        console.log(event, 'event');

        return event.rendering === 'background';
    }
    const select = (selectionInfo) => {
        console.log(selectionInfo, 'event');
        // let a = document.getElementsByClassName('fc-v-event')

        // console.log(a, 'asdas');

        // return event.rendering === 'background';
    }
    const eventAllow = (dropInfo, draggedEvent) => {
        console.log(dropInfo, draggedEvent, 'event');
        if (draggedEvent.id === '999') {
            return dropInfo.start < new Date(2016, 0, 1); // a boolean
        }
        else {
            return true;
        }
    }

    // const [showCreate, setShowCreate] = useState(false);
    // const [createEvent, setCreateEvent] = useState(null);
    // const handleDateClick = (arg) => {
    //     console.log(arg,'argarg');
    //     // const existingEvent = arg.jsEvent.target
    //     // const existingEvent = document.querySelector(`[data-time="${dayjs(arg.dateStr).format('HH:mm:ss')}"]  `);
    //     const existingEvent = document.querySelector(`[data-time="${arg.dateStr}"]  `);
    //     console.log(existingEvent,'existingEvent');

    //     if (existingEvent) {
    //         // 显示已有的元素并更新位置
    //         setCreateEvent(existingEvent);
    //         setShowCreate(true);
    //         return;
    //     }
    //     // 创建新的元素
    //     const el = document.createElement("div");
    //     el.className = "create-event";
    //     el.innerText = "再次点击新建日程";
    //     el.style.backgroundColor = "#41be5e";
    //     el.dataset.start = arg.dateStr;
    //     const timeGridWrapper = document.querySelector(".fc-timegrid .fc-timegrid-body");
    //     console.log(timeGridWrapper,'timeGridWrapper');

    //     timeGridWrapper.appendChild(el);
    //     setCreateEvent(el);
    //     setShowCreate(true);
    // };
    // const handleCreateClick = () => {
    //     console.log('sadasdas');

    //     // 跳转到新建事件页面
    //     setShowCreate(false);
    //     // TODO: 跳转到新建事件页面
    // };
    // const handleDocumentClick = (event) => {
    //     const target = event.target as HTMLElement;
    //     if (!createEvent || createEvent.contains(target)) {
    //         return;
    //     }
    //     setShowCreate(false);
    // };
    // document.addEventListener("click", handleDocumentClick);


    const selectableAreaRef = useRef<HTMLDivElement>(null);

    const handleSelect = (arg: DateSelectArg) => {
        const { start, end } = arg;
        console.log(start, 'endend', end, 'arg', arg);

        const selectableAreaEl = selectableAreaRef.current;
        console.log(selectableAreaEl, 'selectableAreaEl');


        if (selectableAreaEl) {
            selectableAreaEl.style.display = 'block';
            selectableAreaEl.style.top = arg.jsEvent.changedTouches[0].pageY + 'px';
            selectableAreaEl.style.left = arg.jsEvent.changedTouches[0].pageX + 'px';
        }
        console.log(arg.jsEvent.changedTouches[0].pageY, 'arg.jsEvent.pageY', arg.jsEvent);


        // 添加一个特殊的元素
        const newEventBtnEl = document.createElement('View');
        newEventBtnEl.innerHTML = '再次点击新建日程';
        newEventBtnEl.style.position = 'absolute';
        newEventBtnEl.style.top = '50%';
        newEventBtnEl.style.left = '50%';
        newEventBtnEl.style.transform = 'translate(-50%, -50%)';
        newEventBtnEl.style.backgroundColor = '#41be5e';
        newEventBtnEl.style.padding = '8px';
        newEventBtnEl.style.borderRadius = '8px';
        newEventBtnEl.style.fontSize = '16px';
        newEventBtnEl.style.color = '#fff';
        newEventBtnEl.style.cursor = 'pointer';
        newEventBtnEl.style.zIndex = '9999'
        newEventBtnEl.style.width = '100%'
        newEventBtnEl.style.height = '100%'


        // const calendarApi = arg.view.calendar;
        // calendarApi.unselect(); // 清除当前选择
        // if (selectedEvent) {
        //     // // 如果已选择事件存在，说明是第二次点击，此时跳转到新建事件页面
        //     // let url = '/pages/scheduleApp/createSchedule/index?startDate=' + date
        //     // Taro.navigateTo({
        //     //     url
        //     // })
        // } else {
        //     // 如果已选择事件不存在，说明是第一次点击，此时设置事件背景色和文本
        //     arg.jsEvent.target.style.backgroundColor = '#41be5e';
        //     arg.jsEvent.target.innerText = '再次点击新建日程';
        //     setSelectedEvent(arg);
        // }

        // selectableAreaEl.appendChild(newEventBtnEl);
        let mirror = document.querySelector('.fc-event-mirror');
        mirror.appendChild(newEventBtnEl);

        if (mirror) {
            // mirror.style.color = '#fff';
            // mirror.innerHTML= '再次点击新建日程';
            // mirror.style.fontSize = '16px';
            // mirror.appendChild(newEventBtnEl);
            // mirror.addEventListener('click', () => {
            //     console.log('xinjian');

            //     // TODO: 进入新建日程页面
            //     let url = '/pages/scheduleApp/createSchedule/index?startDate=' + date + '&start=' + dayjs(start).format('HH:mm:ss')+ '&end=' + dayjs(end).format('HH:mm:ss')
            //     Taro.navigateTo({
            //         url
            //     })
            // })
        }

        console.log(mirror, 'mirro');


        // 添加新建事件的点击事件

        newEventBtnEl.addEventListener('click', () => {
            // TODO: 进入新建日程页面
            let url = '/pages/scheduleApp/createSchedule/index?startDate=' + date + '&start=' + dayjs(start).format('HH:mm:ss') + '&end=' + dayjs(end).format('HH:mm:ss')
            Taro.navigateTo({
                url
            })
        })

        // 添加点击其他地方隐藏区域的事件
        // window.addEventListener('click', (e) => {
        //     if (selectableAreaEl && !selectableAreaEl.contains(e.target as Node)) {
        //         selectableAreaEl.style.display = 'none';
        //         selectableAreaEl.innerHTML = '';
        //     }
        // })
    }
    const [selectedEvent, setSelectedEvent] = useState(null);
    const handleSelect1 = (selectInfo) => {
        const calendarApi = selectInfo.view.calendar;
        calendarApi.unselect(); // 清除当前选择
        if (selectedEvent) {
            // // 如果已选择事件存在，说明是第二次点击，此时跳转到新建事件页面
            // let url = '/pages/scheduleApp/createSchedule/index?startDate=' + date
            // Taro.navigateTo({
            //     url
            // })
        } else {
            // 如果已选择事件不存在，说明是第一次点击，此时设置事件背景色和文本
            selectInfo.jsEvent.target.style.backgroundColor = '#41be5e';
            selectInfo.jsEvent.target.innerText = '再次点击新建日程';
            setSelectedEvent(selectInfo);
        }
    };
    if (selectedEvent) {
        const { start, end } = selectedEvent;
        selectedEvent.jsEvent.target.addEventListener('click', () => {
            // TODO: 进入新建日程页面
            let url = '/pages/scheduleApp/createSchedule/index?startDate=' + date + '&start=' + dayjs(start).format('HH:mm:ss') + '&end=' + dayjs(end).format('HH:mm:ss')
            Taro.navigateTo({
                url
            })
        })
    }
    const handleSelect2 = (selectInfo) => {
        console.log(selectInfo, 'selectInfo');

        const calendarApi = selectInfo.view.calendar;
        const event = {
            className: 'new-event',
            title: '再次点击新建日程',
            start: selectInfo.startStr,
            end: selectInfo.endStr,
            allDay: selectInfo.allDay,
            display: 'background',
            color: '#41be5e',
            extendedProps: {
                "scheduleTitle": "再次点击新建日程",
                "beAllDay": "0",
                "repeatTime": "0",
                "beSkipHolidays": "0",
                "beCourse": "0",
                "functionLinkInfoList": [],
                "inviteCount": "0",
                "markDone": "0",
                "beExternal": "0",
                "beMeeting": "0",
                "startTime1": dayjs(selectInfo.startStr).format('HH:mm'),
                "endTime1": dayjs(selectInfo.endStr).format('HH:mm')
            }
        };
        calendarApi.addEvent(event); // 添加事件
    };
    const handleEventClick = (clickInfo) => {
        console.log(clickInfo, 'clickInfo');

        if (clickInfo.event.classNames.includes('new-event')) {
            // 如果点击的是新建事件，跳转到新建事件页面
            let url = '/pages/scheduleApp/createSchedule/index?startDate=' + date + '&start='
            Taro.navigateTo({
                url
            })
        }
    };

    const [isCreatingEvent, setIsCreatingEvent] = useState(false);
    const handleSelect3 = (selectInfo) => {
        const calendarApi = selectInfo.view.calendar;
        const event = {
            title: '新建事件',
            start: selectInfo.startStr,
            end: selectInfo.endStr,
            allDay: selectInfo.allDay,
            className: 'new-event'
        };
        calendarApi.addEvent(event);
        setIsCreatingEvent(true);
    };
    const handleUnselect = () => {
        setIsCreatingEvent(false);
    };
    const handleEventClick2 = (clickInfo) => {
        console.log(clickInfo, 'clickInfo11');

        if (clickInfo.event.classNames.includes('new-event')) {
            setIsCreatingEvent(true);
            let url = '/pages/scheduleApp/createSchedule/index?startDate=' + date + '&start='
            Taro.navigateTo({
                url
            })
        }
    };
    // 处理选择时间段的事件
    function handleSelect4(info) {
        const calendarApi = calendarRef.current.getApi();

        // 获取用户选择的开始时间和结束时间
        const start = info.start;
        const end = info.end;

        // 创建一个新的日程对象
        const event = {
            title: '新日程',
            start: start,
            end: end,
            allDay: false
        };

        // 将日程添加到日历中
        calendarApi.addEvent(event);
    }

    return (
        // <View className='schedule-grid' onClick={handleClick}>
        <View className='schedule-grid'>
            <FullCalendar
                plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin,]}
                initialView="timeGridDay" // 初始化在week维度
                selectable={true}
                unselectAuto={true}
                select={handleSelect4}
                // initialView="timelinePlugin" // 初始化在week维度
                // initialView="dayGridMonth" // 初始化在week维度
                // select={select}
                slotEventOverlap={true}
                dragScroll={true}
                unselect={handleUnselect} // 监听fullcalendar的unselect事件
                selectMirror={true}
                selectOverlap={selectOverlap}
                selectMinDistance={60}
                editable={true}//用来设置日历中的日程是否可以编辑. 可编辑是指可以移动, 改变大小等
                eventStartEditable={true}
                eventResizableFromStart={true}
                locale="zh-cn"
                allDaySlot={false} // 不显示all-day
                buttonText={{ today: '今天', month: '月', week: '周', day: '天' }}
                // headerToolbar={false}
                // firstDay={1} // 从周六开始
                scrollTime={'08:00:00'} // 初始滚动条滚动到的时间位置：6点
                slotLabelFormat={{ hour: '2-digit', minute: '2-digit', meridiem: false, hour12: false }} // 左侧时间格式
                defaultTimedEventDuration={'01:00:00'} // 当没有设置endTime时的持续时间为1个小时
                displayEventEnd
                // eventClick={eventClick}
                eventClick={handleEventClick2}
                eventSources={[scheduleList]} // 数据源
                height={'100%'}
                // eventContent={renderEventContent}
                // dateClick={dateClick}
                // dateClick={handleDateClick}
                // dateClick={handleSelect}
                slotDuration={'00:60:00'}
                // timeZone="zh-cn"
                // scrollTime={scrollTime}
                scrollTimeReset={true}
                displayEventTime={false}
                ref={calendarRef}
                nowIndicator={true}
                now={currentTime}
            // showCreateEvent={true}
            />
            <View
                ref={selectableAreaRef}
                style={{ display: 'none', position: 'absolute', padding: '16px' }}
            />
            {/* {showCreateEvent && renderCreateEvent()} */}
        </View>
    )
}

const mainProps = ({ commonData }) => {
    return {
        userInfo: commonData.userInfo,
    }
}

export default connect(mainProps)(App)
